package com.chaos.auth.config;

import com.chaos.framework.model.dto.result.Result;
import com.chaos.framework.model.enums.ResultEnum;
import com.chaos.framework.model.exception.BusinessException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Order(Ordered.HIGHEST_PRECEDENCE)
public class OAuth2ExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        Result result = null;

        if (ex instanceof InvalidClientException) {
            result = Result.of(ResultEnum.INVALID_CLIENT.getCode(), ex.getMessage());
        } else if (ex instanceof InvalidGrantException) {
            result = Result.of(ResultEnum.INVALID_GRANT.getCode(), ex.getMessage());
        } else if (ex instanceof DuplicateKeyException) {
            result = Result.of(ResultEnum.SQL_DUPLICATE_KEY);
        } else if (ex instanceof DataIntegrityViolationException) {
            result = Result.of(ResultEnum.SQL_DATA_INTEGRITY_VIOLATION);
        } else if (ex instanceof BusinessException) {
            result = ((BusinessException) ex).getResult();
        } else {
            result = Result.of(ResultEnum.UNKNOWN_ERROR.getCode(), ex.getMessage());
            ex.printStackTrace();
        }

        // 设置HTTP状态码
        response.setStatus(HttpStatus.OK.value());
        // 设置Content-Type
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 将错误信息写入响应体
            new ObjectMapper().writeValue(response.getWriter(), result);
        } catch (Exception e) {
            // 处理写入响应体过程中的异常
        }

        return new ModelAndView(); // 不需要视图
    }
}

